#!/bin/bash

# LINUX=linux-3.10.105
# BUSYBOX=busybox-1.26.2

init_arch () {
	echo "Init archlinux ..."
	pacman -Syy
	pacman -S --noconfirm wget ncurses flex bison inetutils lbzip2 elfutils \
        qemu-system-x86 seabios gdb dnsmasq procps-ng bridge-utils iptables
}

init_centos () {
	echo "Init centos/fedora ..."
    if [ -f /etc/centos-release ]; then
        ver=$(cat /etc/centos-release | grep -o '[0-9]' | head -1)
        [ "$ver" -ne "7" ] && "only support centos7" && exit 1
    fi

	yum -y install gcc ncurses ncurses-devel bc telnet wget flex bison \
        lbzip2 seabios gdb qemu-system-x86 seabios epel-release \
		elfutils-libelf-devel bridge-utils iptables dnsmasq procps-ng
}

dist="$(. /etc/os-release && echo "$ID")"
case $dist in
    centos|fedora) init_centos ;;
    arch)          init_arch ;;
    *)	echo "only support centos/fedora and arch" && exit 1
esac

# setting up linux source tree
if [ ! -d "$LINUX" ]; then
	sysctl -w net.ipv4.ping_group_range="0 2147483647"
	wget --no-check-certificate https://mirrors.aliyun.com/linux-kernel/v${LINUX:6:1}.x/$LINUX.tar.xz
	tar xf $LINUX.tar.xz
fi

/bin/cp -f ./config $LINUX/.config
yes "" | make -C $LINUX oldconfig

# setting up busybox source tree
if [ ! -d $BUSYBOX ]; then
	#wget https://gitee.com/fjrti/linux-toy/releases/download/v1.0.0/$BUSYBOX.tar.bz2
	wget --no-check-certificate https://busybox.net/downloads/$BUSYBOX.tar.bz2
	tar xf $BUSYBOX.tar.bz2
fi

make -C $BUSYBOX defconfig
# ${LINUX}/scripts/config --file ${BUSYBOX}/.config --enable CONFIG_STATIC
${LINUX}/scripts/config --file ${BUSYBOX}/.config --enable CONFIG_INSTALL_NO_USR
${LINUX}/scripts/config --file ${BUSYBOX}/.config --disable CONFIG_INETD
${LINUX}/scripts/config --file ${BUSYBOX}/.config --disable CONFIG_FEATURE_MOUNT_NFS
yes "" | make -C $BUSYBOX oldconfig
